<!--  -->
<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
        <el-form-item label="菜单名称" prop="menuName">
        <el-input
           v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

         <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="mx-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="mx-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
     </el-form>

     <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="3" :offset="19">
           <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-col>
      
    </el-row>

    <el-table
      v-loading="loading"
      :data="menuList"
      row-key="menuId"
      empty-text="暂无数据"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template v-slot="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="60"></el-table-column>
      <el-table-column prop="perms" label="权限标识" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="routerPath" label="路由path" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="routerName" label="路由name" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormat" width="80"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" 
            type="text" 
            icon="el-icon-edit" 
            @click="handleUpdate(scope.row)"
            
          >修改</el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-plus" 
            @click="handleAdd(scope.row)"
           
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="769px" append-to-body destroy-on-close @open="diaOpen" @opened="diaOpened">
      <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="100px" size="small">

        <el-row :gutter="35">
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                v-model="form.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col> 

          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> 

          <el-col :span="24">
              <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
                <IconSelector v-model="form.icon" type='mx' :clearable="true"/>
              </el-form-item>
            </el-col>  

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="菜单名称" prop="menuName">
							<el-input v-model="form.menuName" placeholder="菜单名称 title" clearable></el-input>
						</el-form-item>
					</el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.menuType != 'F'">
						<el-form-item label="页面类型">
							<el-select v-model="form.pageType" placeholder="请选择页面类型" class="w100" @change="onPageTypeChange">
								<el-option label="普通" value="0"></el-option>
								<el-option label="外链" value="1"></el-option>
                <el-option label="内嵌" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="form.menuType != 'F'">
						<el-form-item label="链接地址">
							<el-input
								v-model="form.linkUrl"
								placeholder="外链/内嵌时链接地址（http:xxx.com）"
								clearable
								:disabled="linkUrlDisFlag"
							>
							</el-input>
						</el-form-item>
					</el-col> 

          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="路由地址" prop="routerPath" >
              <el-input v-model="form.routerPath" placeholder="请输入路由地址 path"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="路由名称" prop="routerName">
              <el-input v-model="form.routerName" placeholder="请输入路由名称 name" />
            </el-form-item>
          </el-col>

          

          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径 component" :readonly = "form.pageType != '0'"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.menuType != 'M'">
            <el-form-item  label="权限标识">
              <el-input v-model="form.perms" placeholder="请输入权限标识"/>
            </el-form-item>
          </el-col>

          

   

          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item  label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio
                  v-for="dict in visibleOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item  label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>

            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item  label="是否缓存">
              <el-radio-group v-model="form.isCache">
                <el-radio label="1">缓存</el-radio>
                <el-radio label="0">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.menuType == 'C'">
						<el-form-item label="是否固定">
              <el-radio-group v-model="form.isAffix">
                <el-radio label="1">固定</el-radio>
                <el-radio label="0">不固定</el-radio>
              </el-radio-group>
						</el-form-item>
					</el-col>

          <!-- <el-col :span="12" v-if="form.menuType == 'C'">
						<el-form-item label="是否外链">
              <el-radio-group v-model="form.isLink" @change="isLinkChange">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="form.menuType == 'C'">
						<el-form-item label="是否内嵌">
              <el-radio-group v-model="form.isIframe" @change="isIframChange">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
						</el-form-item>
					</el-col> -->
          

        </el-row>
        
      </el-form>

      <template #footer>
        <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
    </el-dialog>

    
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  getCurrentInstance,
} from "vue";
import { listMenu,getMenu, delMenu, addMenu, updateMenu} from "@/api/system/menu.js";
import Treeselect from 'vue3-treeselect'
import 'vue3-treeselect/dist/vue3-treeselect.css'
import IconSelector from '@/components/iconSelector/index.vue';
export default defineComponent({
  name: "SystemMenu",
  components:{Treeselect,IconSelector},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示状态数据字典
      visibleOptions: [],
      // 菜单状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  setup() {
    const {proxy} = getCurrentInstance()
    const queryFormRef = ref(null)
    const menuFormRef = ref(null)
    const data = reactive({
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示状态数据字典
      visibleOptions: [],
      // 菜单状态数据字典
      statusOptions: [],
      queryParams: {
        menuName: undefined,
        status: undefined
      },
      linkUrlDisFlag: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        routerPath: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ],
        routerName: [
          { required: true, message: "路由名称不能为空", trigger: "blur" }
        ]
      },
    });

    // 查询菜单数据
    const getList = () => {
      listMenu(data.queryParams).then(response => {
        data.menuList = proxy.handleTree(response.data, "menuId");
      });
    }
    
    // 表格 字段数据 转换
    const statusFormat = (row) => {
      if (row.menuType == "F") {
        return "";
      }
      return proxy.selectDictLabel(data.statusOptions, row.status);
    }

    const normalizer = (node) => {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    }

    const getTreeselect = () => {
      listMenu().then(response => {
        data.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = proxy.handleTree(response.data, "menuId");
        data.menuOptions.push(menu);
        console.log("treeSelect ....")
        console.log(data.menuOptions)
      });
    }

    // 搜索按钮
    const handleQuery = () => {
      getList();
    }
    
    // 表单重置按钮操作
    const resetQuery = () => {
      queryFormRef.value.resetFields()
      handleQuery()
    }

    // 取消按钮
    const cancel = () => {
      data.open = false;
      reset();
    }

    const onPageTypeChange = (value) =>{
        console.log(value)

        if(value == '0'){
           data.form.linkUrl = ''
           data.form.component = ''
           data.linkUrlDisFlag = true
        }else if(value == '1'){
          data.form.routerPath = ''
          if(data.form.menuType == 'C'){
              data.form.component = 'layout/routerView/link'
          }
          data.linkUrlDisFlag = false
        }else {
          data.form.component = 'layout/routerView/iframes'
          data.linkUrlDisFlag = false
        }
    }
    
    // 是否外链 change事件
    const isLinkChange = (value) => {
        console.log(value)
        if(value == 1){
            // 启用 链接地址
            data.form.isIframe = '0'
            data.linkUrlDisFlag = false
        }else{
          // 禁用 链接地址
          data.linkUrlDisFlag = true
        }
    }

    const isIframChange = (value) =>{
      if(value == 1){
          data.form.isLink = '0'
          data.linkUrlDisFlag = false
      }else{
        data.linkUrlDisFlag = true
      }
    }

    const submitForm = () => {
      
      menuFormRef.value.validate(valid => {
        console.log(data.form)
        if (valid) {
          if (data.form.menuId != undefined) {
            console.log('修改')
            updateMenu(data.form).then(() => {
              proxy.msgSuccess("修改成功");
              data.open = false;
              getList();
            });
          } else {
            console.log('新增')            
            addMenu(data.form).then(() => {
              proxy.msgSuccess('新增成功')
              data.open = false;
              getList();
            });
          }
        }
      });
    }
    
    // 菜单新增表单数据重置
    const reset = () => {
      data.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,   // 菜单名称
        icon: undefined,       // 图标icon
        menuType: "M",         // 菜单类型
        pageType: "0",         // 页面类型  普通 外链 内嵌
        orderNum: undefined,   // 显示排序         
        isCache: "1",          // 是否缓存
        isAffix: "0",          // 是否固定 tagView
        isLink: "0",           // 是否外链
        isIframe: "0",         // 是否内嵌
        visible: "0",          // 显示状态
        status: "0"            // 菜单状态 停用/正常
      };
      
    }

     /** 修改按钮操作 */
    const handleUpdate = (row) => {
      console.log('row info')
      console.log(row)
      reset();
      getTreeselect();
      getMenu(row.menuId).then(response => {
        data.form = response.data;
        data.form.orderNum = parseInt(row.orderNum)
        data.open = true;
        data.title = "修改菜单";
      });
    }

    const diaOpen = () => {
        
    }

    const diaOpened = () => {
        console.log(data.form)
      
    }

    // 新增 菜单 按钮操作
    const handleAdd = (row) => {
      reset()
      //menuFormRef.value.resetFields()
      getTreeselect()
      if (row != null && row.menuId) {
        data.form.parentId = row.menuId;
      } else {
        data.form.parentId = 0;
      }
      data.open = true;
      data.title = "添加菜单";
    }

    const parseTime = proxy.parseTime
    
    // vue2中在 created生命周期中写，vue3中在 setup中
    getList()

    proxy.getDicts("sys_show_hide").then(response => {
      data.visibleOptions = response.data;
    });
    proxy.getDicts("sys_normal_disable").then(response => {
      data.statusOptions = response.data;
    });

    const refData = toRefs(data);
    return {
      queryFormRef,
      menuFormRef,
      ...refData,
      handleQuery,
      resetQuery,
      handleAdd,
      handleUpdate,
      parseTime,
      normalizer,
      diaOpen,
      diaOpened,
      cancel,
      submitForm,
      isLinkChange,
      isIframChange,
      onPageTypeChange,
      statusFormat,
    };
  },
  
});
</script>
<style lang="scss" scoped></style>
